from django.shortcuts import render,HttpResponse,HttpResponseRedirect,reverse
import uuid
from add.models import UserModel
# Create your views here.
#def add(request,):
#    a = request.GET["a"]
 #   b = request.GET["b"]
 #   a=int(a)
 #   b=int(b)
 #   return HttpResponse(str(a+b))
#def index(request):
  #  return render(request,'index.html')
def index(request):
    mysessionid = request.COOKIES.get("mysessionid_cookie")
    username = request.session.get(mysessionid,None)
    if username:
        return HttpResponse('这是博客主页')
    else:
        #return HttpResponse('这是博客主页')
        return HttpResponseRedirect(reverse("login_page"))
def login(request):
    if request.method == "GET":
        return render(request,"login.html")
    else: #POST
        print("post")
        #效验密码和用户
        username = request.POST.get("username",None)
        print(username)
        password = request.POST.get("password",None)
        print(password)
        userModel = UserModel.objects.filter(name = username,password = password).first()
        print(userModel)
        if userModel:

        #给客户端设定cookie
            print(666)
            response= HttpResponseRedirect(reverse("index_page"))
            mysessionid = str(uuid.uuid4())
            response.set_cookie('mysessionid_cookie',mysessionid)
       #设置session的值
            request.session[mysessionid]=userModel.name
            return response
        else:
            return HttpResponse('用户名或密码错误')